package com.yp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yp.common.BaseResponse;
import com.yp.common.ErrorCode;
import com.yp.common.ResultUtils;
import com.yp.exception.BusinessException;
import com.yp.model.domain.User;
import com.yp.model.domain.request.UserLoginRequest;
import com.yp.model.domain.request.UserRegisterRequest;
import com.yp.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.yp.constant.UserConstant.ADMIN_ROLE;
import static com.yp.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @BelongsProject: useer-center
 * @BelongsPackage: com.yp.controller
 * @Author: FUHB
 * @email:1269159180@qq.com
 * @Description: TODO
 * @Version: 1.0
 */

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
//@CrossOrigin(origins = {"http://localhost:3000"})
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 获取用户的登录态
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrent(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User userCurrent = (User) userObj;
        if (userCurrent == null){
//            return null;
            throw new BusinessException(ErrorCode.NOT_LOGIN,"未登录");
        }
        Long id = userCurrent.getId();
        User user = userService.getById(id);
//        return userService.getSafetyUser(user);
        User result = userService.getSafetyUser(user);
        return ResultUtils.success(result);
    }

    /**
     *  用户注册功能
     * @param userRegisterRequest 用户注册模版
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
//        System.out.println("userRegisterRequest = " + userRegisterRequest);
        if (userRegisterRequest == null) {
//            return ResultUtils.error(ErrorCode.PARAM_ERROR);
            throw new BusinessException(ErrorCode.PARAM_ERROR,"注册参数为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String pantCode = userRegisterRequest.getPantCode();

        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword,pantCode)) {
//            return null;
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }

//        return userService.userRegister(userAccount, userPassword, checkPassword,pantCode);
        long result = userService.userRegister(userAccount, userPassword, checkPassword, pantCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     * @param userLoginRequest 用户登录模版参数
     * @param request 前端的请求
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {

        if (userLoginRequest == null) {
//            return null;
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();


        if (StringUtils.isAllBlank(userAccount, userPassword)) {
//            return null;
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }

//        return userService.userLogin(userAccount, userPassword, request);
        User result = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(result);
    }

    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {

        if (request == null){
//            return null;
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }

//        return userService.userLogout(request);
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * @param username 查询的用户名字
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String username, HttpServletRequest request) {

        if (!isAdmin(request)) {
//            return new ArrayList<>();
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            userQueryWrapper.eq("username", username);
        }

        List<User> userList = userService.list(userQueryWrapper);
//        return userList.stream().map(user -> {
//            return userService.getSafetyUser(user);
//        }).collect(Collectors.toList());//需要解释
        List<User> result = userList.stream().map(user -> {
            return userService.getSafetyUser(user);
        }).collect(Collectors.toList());

        return ResultUtils.success(result);
    }

    /**
     * 删除用户
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {

        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }

        if (id <= 0) {
//            return null;
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }

//        return userService.removeById(id);
        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList){

        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        List<User> userList = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(userList);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return false 不是 true 是
     */

    private boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            return false;
        }

        return true;
    }


}
